import React from 'react'
import PropTypes from 'prop-types'
import marked from 'marked'
import Helmet from 'react-helmet'
import dateFormat from 'dateformat'
import {
  inject,
  observer,
} from 'mobx-react'
import green from '@material-ui/core/colors/green'
import { withStyles } from '@material-ui/core/styles'
import Paper from '@material-ui/core/Paper'
import { CircularProgress } from '@material-ui/core/CircularProgress'
import Button from '@material-ui/core/Button'
import IconReply from '@material-ui/icons/Reply'
import SimpleMDE from 'react-simplemde-editor'
import Container from '../layout/container'
import { topicDetailStyle } from './styles'
import Reply from './reply'
// import TopicStore from '../../store/topic-store'

@inject((stores) => {
  return {
    topicStore: stores.topicStore,
    user: stores.appState.user,
  }
}) @observer
class TopicDetail extends React.Component {
  static contextTypes = {
    router: PropTypes.object,
  }

  constructor(props) {
    super(props);
    this.state = {
      newReply: '',
    }
    this.handleNewReplyChange = this.handleNewReplyChange.bind(this)
    this.goToLogin = this.goToLogin.bind(this)
    this.doReply = this.doReply.bind(this)
  }

  componentDidMount() {
    console.log("componentDidMount运行\n,getTopicId:", this.getTopicId()) // eslint-disable-line
    const id = this.getTopicId()
    this.props.topicStore.getTopicDetail(id)
  }

  getTopicId() {
    return this.props.match.params.id
  }

  handleNewReplyChange(value) {
    this.setState({
      newReply: value,
    })
  }

  goToLogin() {
    this.context.router.history.push('/user/login')
  }

  doReply() {
    const id = this.getTopicId()
    const topic = this.props.topicStore.detailMap[id]
    topic.doReply(this.state.newReply)
      .then(() => {
        this.setState({
          newReply: '',
        })
      }).catch((err) => {
        console.error(err) // eslint-disable-line
      })
  }

  render() {
    const {
      classes,
      user,
    } = this.props
    // const id = this.getTopicId() // 通过react-router生成的match对象获取url的params参数
    // const topic = this.props.topicStore.detailMap[id]
    const topic = this.props.topicStore.topics[2]
    if (!topic) { // topic 不存在加载 loading
      return (
        <Container>
          <section className={classes.loadingContainer}>
            <CircularProgress style={{ color: green[500] }} size={100} />
          </section>
        </Container>
      )
    }

    // 把内容放到 p 标签下，但是是直接塞入 html，不转义html标签
    return (
      <div>
        <Container key={topic.author_id}>
          <Helmet>
            <title>{topic.title}</title>
          </Helmet>
          <header className={classes.header}>
            <h3>{topic.title}</h3>
          </header>
          <section className={classes.body}>
            <p dangerouslySetInnerHTML={{ __html: marked(topic.content) }} />  {/* eslint-disable-line */}
          </section>
        </Container>
        {
          topic.createReplies && topic.createdReplies.length > 0
            ? (
              <Paper elevation={4} className={classes.replies}>
                <header className={classes.replyHeader}>
                  <span>我的最近回复</span>
                  <span>{`${topic.createdReplies.length}条`}</span>
                </header>
                {
                  topic.createdReplies.map(reply => (
                    <Reply
                      key={reply.id}
                      reply={Object.assign({}, reply, {
                        author: {
                          avatar_url: user.info.avatar_url,
                          loginname: user.info.loginname,
                        },
                      })}
                    />
                  ))
                }
              </Paper>
            ) : null
        }

        <Paper key={topic.id} elevation={4} className={classes.replies}>
          <header className={classes.replyHeader}>
            <span>{`${topic.reply_count} 回复`}</span>
            <span>{`最新回复 ${dateFormat(topic.last_reply_at, 'yy-mm-dd')}`}</span>
          </header>
          {
            user.isLogin
              ? (
                <section className={classes.replyEditor}>
                  <SimpleMDE
                    onChange={this.handleNewReplyChange}
                    value={this.state.newReply}
                    options={{
                      toolbar: false,
                      autoFocus: false,
                      spellChecker: false, // 英文拼写检查
                      placeholder: '添加您的精彩回复',
                    }}
                  />
                  <Button
                    variant="fab"
                    color="primary"
                    onClick={this.doReply}
                    className={classes.replyButton}
                  >
                    <IconReply />
                  </Button>
                </section>)
              : null
          }
          {
            !user.isLogin
              ? (
                <section className={classes.notLoginButton}>
                  <Button variant="contained" color="secondary" onClick={this.goToLogin}>
                    登录并进行回复
                  </Button>
                </section>
              )
              : null
          }
          <section>
            {
              topic.replies.map(reply => <Reply reply={reply} key={reply.id} />)
            }
          </section>
        </Paper>
      </div>
    )
  }
}

TopicDetail.wrappedComponent.propTypes = {
  topicStore: PropTypes.object.isRequired,
  user: PropTypes.object.isRequired,
}

TopicDetail.propTypes = {
  classes: PropTypes.object.isRequired,
  match: PropTypes.object.isRequired,
}

export default withStyles(topicDetailStyle)(TopicDetail)
